package com.xjnt.tvos.tvlibs.jsbridge.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 *
 * 传输数据构建器
 *
 * Created by caoyong on 18-1-9.
 */

public class DataBuilder {


    private JSONObject mParams;

    private DataBuilder() {
        mParams = new JSONObject();
    }

    /**
     * 请求格式
     * {
     *     methodName: 请求目标的方法名,
     *     callbackId: 请求自身回调函数标识,
     *     notifyName: 请求自身的统一通知方法名,
     *     params: {...} 请求数据
     * }
     *
     * 响应格式
     * {
     *     status: 状态 0 失败 1 成功,
     *     msg: 状态消息,
     *     id: 目标回调函数标识,
     *     data: {...} 响应数据
     * }
     *
     * @param jsonString JSON格式的字符串
     * @return DataBuilder
     */
    public static DataBuilder build(String jsonString) {
        DataBuilder dataBuilder = new DataBuilder();
        dataBuilder.mParams = JSON.parseObject(jsonString);
        return dataBuilder;
    }

    public static DataBuilder build() {
        DataBuilder dataBuilder = new DataBuilder();
        dataBuilder.mParams = new JSONObject();
        return dataBuilder;
    }

    @SuppressWarnings("unchecked")
    public <T> T get(String key, Class<T> clazz) {
        if (null != clazz) {
            Object obj = mParams.get(key);
            if(clazz.isPrimitive()) {
                return ((T) obj);
            } else if (clazz.isInstance(obj)) {
                return clazz.cast(obj);
            } else {
                throw new RuntimeException("Cannot be cast " + obj.getClass() + " to " + clazz.getName());
            }
        }
        return null;
    }

    public void put(String key, Object value) {
        mParams.put(key, value);
    }

    public void clear() {
        mParams.clear();
    }

    public void setResponseStatus(int status, String msg) {
        mParams.put(ParamConsts.KEY_RESPONSE_STATUS, status);
        mParams.put(ParamConsts.KEY_RESPONSE_MSG, msg);
    }

    public boolean isRequest() {
        return !mParams.containsKey(ParamConsts.KEY_RESPONSE_ID);
    }

    public String toDataString() {
        return mParams.toJSONString();
    }
}
